package com.ocom.mjrecode.controller;

import com.ocom.common.constant.MjRecodeUrl;
import com.ocom.common.entity.access.EntityMjDeviceInfo;
import com.ocom.common.entity.mjrecode.MjRecord;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.IPUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.mjrecode.feign.AccessClientService;
import com.ocom.mjrecode.service.MjRecodeService;
import com.ocom.mjrecode.utils.SnowflakeIdWorker;
import com.ocom.redis.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;

@RestController
public class MjLogController {


	private Logger logger = LoggerFactory.getLogger(MjLogController.class);

	@Autowired
	private MjRecodeService mjRecodeService;

	@Autowired
	private AccessClientService accessClientService;

	@Resource
	private RedisUtil redisUtil;
	/**
	 * 替换原有
	 * @param mjRecord
	 * @return
	 */
	@PostMapping(MjRecodeUrl.URL_Record)
	public Result saveAccessRecord(@RequestBody MjRecord mjRecord){
		if(!redisUtil.lock("lockMjOrder:"+mjRecord.getComId() + ":"+ mjRecord.getDeviceNo() + ":" + mjRecord.getRecordId()+":"+mjRecord.getPCode()+":"+mjRecord.getPName(),300)){
			return ResultUtil.success();
		}

		Integer workId=(Integer)redisUtil.hmGet("Snowflake:workerId", IPUtils.getLocalPort());
		if(workId==null || workId>28){
			Long nowWorkId=redisUtil.incr("Snowflake:workerId:incr",1l);
			if(nowWorkId>28){
				redisUtil.del("Snowflake:workerId:incr");
				redisUtil.del("Snowflake:workerId");
				nowWorkId=redisUtil.incr("Snowflake:workerId:incr",1l);
			}
			workId=nowWorkId.intValue();
			redisUtil.hmSet("Snowflake:workerId",IPUtils.getLocalPort(),workId);
		}

		SnowflakeIdWorker snowflakeIdWorker=  new SnowflakeIdWorker(workId,2,2);

//		mjRecord.setId(Math.abs(idGenerator.generateId().intValue()));
		mjRecord.setId(snowflakeIdWorker.nextId());
		mjRecord.setYctRetcode(mjRecord.getCheckStatus());

		if(!CommonUtil.isNull(mjRecord.getDeviceName())){
			mjRecord.setDeviceName(mjRecord.getDeviceName());
		} else {
			try {
				Result<EntityMjDeviceInfo> result = accessClientService.GetDeviceByDeviceNo(mjRecord.getDeviceNo(), mjRecord.getComId().longValue());
				if (200 != result.getCode() || null == result.getData()) {
					mjRecord.setDeviceName("门禁设备");
				} else {
					EntityMjDeviceInfo entityMjDeviceInfo = result.getData();
					mjRecord.setDeviceName(entityMjDeviceInfo.getDeviceName());
					mjRecord.setDeviceVerType(entityMjDeviceInfo.getDeviceVerType());
				}
			}catch (Exception e){
				e.printStackTrace();
				mjRecord.setDeviceName("门禁设备");
			}

		}
		try {
			mjRecord.setMonthValue(DateUtils.getStrDate(mjRecord.getOpenTime(),"yyyyMM"));
		}catch (Exception e){
			return ResultUtil.error(ResultEnum.Err_2032);
		}
		mjRecord.setCreateTime(new Date());

		try {
			int i = mjRecodeService.add(mjRecord);
		}catch (Exception e){
			logger.info("门禁记录上传报错: 提交数据库  数据【{}】异常:【{}】",mjRecord,e.getMessage());
			return ResultUtil.error(ResultEnum.Err_2016);
		}
		return ResultUtil.success();
	}


//	@PostMapping(value = MjRecodeUrl.URL_YkmRecord,consumes = "application/json;charset=utf-8")
//	public Result saveYkmRecord(@RequestBody YctUsefulInfo yctUsefulInfo){
//		System.out.println(yctUsefulInfo);
//		return ResultUtil.success();
//	}

	/**
	@PostMapping(value = MjRecodeUrl.URL_YkmRecord,consumes = "application/json;charset=utf-8")
	public Result saveYkmRecord(@RequestBody Map<String,Object> map){
		MjRecord mjRecord=new MjRecord();
//		mjRecord.setId(Math.abs(idGenerator.generateId().intValue()));

		SnowflakeIdWorker snowflakeIdWorker=  new SnowflakeIdWorker(2,2,2);

		mjRecord.setId(snowflakeIdWorker.nextId());

		String time= (String) map.get("accessTime");
		//类型
		Integer type= (Integer) map.get("type");
		//操作类型
		Integer operateType= (Integer) map.get("operateType");


		mjRecord.setComId((Integer) map.get("companyId"));
//		mjRecord.setPCode((String) map.get("idnum"));
		mjRecord.setPName("未知人员");
		mjRecord.setDeviceNo((String) map.get("machNo"));
		mjRecord.setDeviceName("门禁设备");
		mjRecord.setData((String) map.get("data"));
//		mjRecord.setYct((String) map.get("yct"));

		if(map.containsKey("regionId")){
			mjRecord.setRegionId((Integer)map.get("regionId"));
		}
		if(map.containsKey("regionName")){
			mjRecord.setRegionName((String)map.get("regionName"));
		}
		if(map.containsKey("areaId")){
			mjRecord.setAreaId((Integer)map.get("areaId"));
		}
		if(map.containsKey("areaName")){
			mjRecord.setAreaName((String)map.get("areaName"));
		}

		String yct=(String) map.get("yct");

		logger.info("门禁记录上传羊城通 ：yct【{}】",yct);

		final BASE64Decoder decoder = new BASE64Decoder();

		try {
//			byte[] yt6 = Base64.getDecoder().decode(yct.getBytes(StandardCharsets.UTF_8));
//			String uy = new String(yt6);
			String uy = new String(decoder.decodeBuffer(yct), "UTF-8");
			Gson gson = new Gson();
			Map<String, Object> map1 = gson.fromJson(uy, Map.class);
			List<Map> list = gson.fromJson((String) map1.get("data"), List.class);
			Map<String, Object> stringObjectMap = new HashMap<>();
			for (Map<String, Object> map2 : list) {
				for (Map.Entry entry : map2.entrySet()) {
					stringObjectMap.put((String) entry.getKey(), entry.getValue());
				}
			}

			YtcResult ytcResult= JSON.parseObject(JSON.toJSONString(stringObjectMap),YtcResult.class);

			logger.info("门禁记录上传羊城通 YtcResult ：【{}】",ytcResult);
			String idCard ="";
			try {
				idCard = ytcResult.getSqfydsryResult().getIdentityNum();
			}catch (Exception e){
			}
			if(idCard.equals("")){
				try {
					idCard = ytcResult.getIdentityResult().getIdentity();
				}catch (Exception e){
				}
			}
			mjRecord.setPCode(idCard);
			mjRecord.setPName(ytcResult.getSqfydsryResult().getName());
			try{
				mjRecord.setPPhone(ytcResult.getHsResult().getData().getData().get(0).getSJHM());
			}catch (Exception e){
			}

			mjRecord.setCodeColor(ytcResult.getYkmResult().getData().getData().get(0).getJKMYS());
			try{
				mjRecord.setColorTime(DateUtil.getDate(ytcResult.getSkmResult().getData().getCheckTime(),"yyyy-MM-dd HH:mm:ss"));
			}catch (Exception e){
				mjRecord.setColorTime(new Date());
			}

//			System.out.println(ytcResult.getSkmResult().getData().getCheckTime());
//			System.out.println(ytcResult.getSkmResult().getData().getReason());
//
//			System.out.println(ytcResult.getYmResult().getData().getData().size());
//
//			System.out.println(ytcResult.getYkmResult().getData().getData().get(0).getJKMYS());

			List<hsResultDataDataVo> data34= ytcResult.getHsResult().getData().getData();
			Date hs1=null;  //时间
			String hs2="";	//结果
			try {
				for (hsResultDataDataVo vo:data34){
					Date t= DateUtil.getDate(vo.getJCJGTBSJ(),"yyyy-MM-dd HH:mm:ss");
					if(hs1==null || hs1.compareTo(t)<0){
						hs1=t;
						hs2=vo.getJCJG();
					}
				}
			}catch (Exception e){
			}
			if(hs1!=null){
				mjRecord.setHsResult(hs2);
				mjRecord.setHsTime(hs1);
			}
			List<hs1ResultDataDataVo> data78= ytcResult.getHs1Result().getData().getData();
			try {
				for (hs1ResultDataDataVo vo:data78){
					Date t= DateUtil.getDate(vo.getJc_rq(),"yyyy-MM-dd HH:mm:ss");
					if(hs1==null || hs1.compareTo(t)<0){
						hs1 = t;
						hs2=vo.getJcjg();
					}
				}
			}catch (Exception e){
			}
			if(hs1!=null){
				mjRecord.setHsResult(hs2);
				mjRecord.setHsTime(hs1);
			}else{
				mjRecord.setHsResult("未核酸");
				mjRecord.setHsTime(new Date());
			}
			List<ymResultDataDataVo> data56 = ytcResult.getYmResult().getData().getData();
			Date ymTime=null;  //时间
			try {
				for (ymResultDataDataVo vo:data56){
					Date t= DateUtil.getDate(vo.getInoculationdate(),"yyyy-MM-dd HH:mm:ss");
					if(ymTime==null || ymTime.compareTo(t)<0){
						ymTime=t;
					}
				}
			}catch (Exception e){
			}
			if(ymTime!=null){
				mjRecord.setYmNum(ytcResult.getYmResult().getData().getData().size());
				mjRecord.setYmTime(ymTime);
			}else{
				mjRecord.setYmNum(0);
				mjRecord.setYmTime(new Date());
			}
		}catch (Exception e){
			logger.info("门禁记录上传##记录异常:请求参数:【{}】,返回参数:【{}】",map,e.getMessage());
		}
		try {
			mjRecord.setOpenTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time));
		}catch (Exception e){
			mjRecord.setOpenTime(new Date());
		}
		mjRecord.setOpenMode(operateType);
		mjRecord.setOpenState((Integer) map.get("openStatus"));
		mjRecord.setOpenInfo((String) map.get("color"));
		mjRecord.setCreateTime(new Date());
		mjRecord.setMonthValue(time.substring(0,7).replace("-",""));

		logger.info("门禁记录上传羊城通 mjRecord ：【{}】",mjRecord);

		mjRecodeService.add(mjRecord);
		return ResultUtil.success();
	}
	**/


	@GetMapping("/test1")
	public Integer test1(){
		MjRecord mjRecord =new MjRecord();
		mjRecord.setId(1l);
		Random random=new Random();
		int rand=random.nextInt(9);
		rand++;
		mjRecord.setComId(rand);
		mjRecord.setMonthValue("202201");
		mjRecodeService.add(mjRecord);
		System.out.println(34444);
		return 123;
	}

	@GetMapping("/test")
	public Integer test(){
		return 123;
	}

}
